﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Log;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;

namespace LiMinCRMPlugin.InterfaceDocking
{
    [Kingdee.BOS.Util.HotUpdate]
    public class GetAvailableQuantity1 : AbstractWebApiBusinessService
    {
        //固定写法,GetCust和上面类名称一致
        public GetAvailableQuantity1(KDServiceContext context)
            : base(context)
        {
        }
        //接收Json, 返回JObject
        public string ExecuteService(string parameter)
        {
            //{
            //"data":
            //{
            //"FStockOrgNubmer": "101",
            //"FMaterialNumber": "001",
            //"RequirementDate": "2024-01-19"
            //}
            //}
            string sql_insert = @"/*dialect*/insert into A_WebApiContent(FContent,Fdate,ftype) values ('" + parameter + "','" + DateTime.Now.ToString() + "','预计可发量查询')";
            DBUtils.Execute(this.KDContext.Session.AppContext, sql_insert);

            string[] FentryID_0 = new string[0];
            string ApiResult = "";//接口返回json

            ReturnJson rs = new ReturnJson();
            var request = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(parameter);//转换
            if (request.Count > 0)
            {
                var reqModel = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(request["data"].ToString());//转换
                string FStockOrgNubmer = reqModel["FStockOrgNubmer"].ToString();//组织编码
                string org_sql = @"/*dialect*/ SELECT FOrgID from T_ORG_Organizations where FNUMBER='" + FStockOrgNubmer + "'";
                DataTable org_dt = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, org_sql).Tables[0];
                string FrogId = "";
                if (org_dt != null && org_dt.Rows.Count > 0)
                {
                    FrogId = org_dt.Rows[0][0].ToString();
                }
                string FMaterialNumber = reqModel["FMaterialNumber"].ToString();//物料编码

                string Material_sql = @"/*dialect*/ SELECT FMATERIALID from T_BD_MATERIAL where FNUMBER='" + FMaterialNumber + "'";
                DataTable Material_dt = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, Material_sql).Tables[0];
                string FMaterialId = "";
                if (Material_dt != null && Material_dt.Rows.Count > 0)
                {
                    FMaterialId = Material_dt.Rows[0][0].ToString();
                }

                string RequirementDate = reqModel["RequirementDate"].ToString();//需求日期
                //判断日期是否为当月 当月执行查询返回数量，未来次月不进行查询直接返回
                if (FrogId != "")
                {
                    if (FMaterialId != "")
                    {
                        if (RequirementDate != "") //必须传递需求日期
                        {

                            DateTime RequirementdateTime = Convert.ToDateTime(RequirementDate);//需求日期
                            DateTime datetime = DateTime.Now;//当前日期
                            //需求日期必须大于当前日期
                            if (RequirementdateTime >= datetime)
                            {
                                //当月
                                if (RequirementdateTime.Month == datetime.Month)
                                {
                                    decimal Qty = 0;//总数量


                                    string sql_str = @"/*dialect*/ SELECT ISNULL(sum(TI.FBASEQTY),0) FBASEQTY
                            FROM T_STK_INVENTORY TI
                            INNER JOIN T_BD_MATERIAL TM ON TI.FMATERIALID = TM.FMASTERID
                                AND TI.FSTOCKORGID = TM.FUSEORGID
                            INNER JOIN T_BD_MATERIALSTOCK TMS ON TM.FMATERIALID = TMS.FMATERIALID
                            LEFT JOIN T_BD_LOTMASTER TL ON TI.FLOT = TL.FMASTERID
                                AND TI.FSTOCKORGID = TL.FUSEORGID AND TL.FBIZTYPE = '1'
                            WHERE TI.FISEFFECTIVED = '1' and FKEEPERTYPEID = 'BD_KeeperOrg'
                            and FOWNERTYPEID = 'BD_KeeperOrg' and TI.FMATERIALID = '" + FMaterialId + "' and FSTOCKERID = '" + FrogId + "' " +
                            " and FKEEPERID = '" + FrogId + "'";
                                    DataTable Inventory_dt = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, sql_str).Tables[0];
                                    decimal BaseQty = 0;
                                    if (Inventory_dt != null && Inventory_dt.Rows.Count > 0)
                                    {
                                        BaseQty = Convert.ToDecimal(Inventory_dt.Rows[0][0]);
                                        //当前库存
                                        Qty = Qty + BaseQty;
                                    }

                                    //查询预计出
                                    string order = @"/*dialect*/ select isnull(sum(FBaseRemainOutQty),0) FBaseRemainOutQty from 
                                    T_SAL_ORDERENTRY a
                                    inner join T_SAL_ORDERENTRY_D b
                                    on a.FENTRYID=b.FENTRYID
                                    inner join T_SAL_ORDERENTRY_R c
                                    on a.FENTRYID=c.FENTRYID
                                     where a.FMATERIALID='" + FMaterialId + "' and a.FStockOrgId='" + FrogId + "'  and b.FDeliveryDate<='" + RequirementDate + "'";
                                    DataTable order_dt = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, order).Tables[0];
                                    decimal OrderBaseQty = 0;
                                    if (order_dt != null && order_dt.Rows.Count > 0)
                                    {
                                        OrderBaseQty = Convert.ToDecimal(order_dt.Rows[0][0]);
                                        //查询预计出
                                        Qty = Qty - OrderBaseQty;
                                    }

                                    //查询预计入
                                    string Prd_sql = @"/*dialect*/  select isnull(sum(FBaseNoStockInQty),0) FBaseNoStockInQty from 
                                    T_PRD_MOENTRY a
                                    inner join T_PRD_MOENTRY_Q b
                                    on a.FENTRYID=b.FENTRYID
                                    where FMATERIALID='" + FMaterialId + "' and FStockInOrgId='" + FrogId + "' and FPlanFinishDate<='" + RequirementDate + "'";
                                    DataTable Prd_dt = DBUtils.ExecuteDataSet(this.KDContext.Session.AppContext, Prd_sql).Tables[0];
                                    decimal PrdBaseQty = 0;
                                    if (Prd_dt != null && Prd_dt.Rows.Count > 0)
                                    {
                                        PrdBaseQty = Convert.ToDecimal(Prd_dt.Rows[0][0]);
                                        //查询预计出
                                        Qty = Qty + PrdBaseQty;
                                    }

                                    Dictionary<string, string> Msg = new Dictionary<string, string>();
                                    Msg.Add("", "读取成功！");
                                    rs = JsonResult("", "", MsgError(Msg), true, 9, FentryID_0);
                                }
                                else//未来不是当月
                                {
                                    Dictionary<string, string> Msg = new Dictionary<string, string>();
                                    Msg.Add("", "非本月生产计划！");
                                    rs = JsonResult("", "", MsgError(Msg), false, 9, FentryID_0);
                                }
                            }
                            else//需求日期小于当前日期
                            {
                                Dictionary<string, string> Msg = new Dictionary<string, string>();
                                Msg.Add("", "需求日期必须大于当前日期！");
                                rs = JsonResult("", "", MsgError(Msg), false, 9, FentryID_0);
                            }
                        }
                        else
                        {
                            Dictionary<string, string> Msg = new Dictionary<string, string>();
                            Msg.Add("", "需求日期不能为空");
                            rs = JsonResult(RequirementDate, "", MsgError(Msg), false, 11, FentryID_0);
                        }
                    }
                    else//物料为空
                    {
                        Dictionary<string, string> Msg = new Dictionary<string, string>();
                        Msg.Add("", "物料不能为空");
                        rs = JsonResult(RequirementDate, "", MsgError(Msg), false, 11, FentryID_0);
                    }
                }
                else//组织为空
                {
                    Dictionary<string, string> Msg = new Dictionary<string, string>();
                    Msg.Add("", "组织不能为空");
                    rs = JsonResult(RequirementDate, "", MsgError(Msg), false, 11, FentryID_0);
                }

            }
            else
            {
                Dictionary<string, string> Msg = new Dictionary<string, string>();
                Msg.Add("", "Json格式不正确！");
                rs = JsonResult("", "", MsgError(Msg), false, 8, FentryID_0);
            }
            string returnJson = "";

            var resultjson = JsonConvert.SerializeObject(rs);
            returnJson = resultjson.ToString();
            GetLog(rs.Result.ResponseStatus.Errors[0].Message, "预计可发量查询", "AR_receivable", "40");


            return returnJson;
        }

        private K3CloudApiClient Login()
        {
            K3CloudApiClient client = new K3CloudApiClient(GlobalParameters.CloudUrl);
            var loginResult = client.LoginByAppSecret(GlobalParameters.db, GlobalParameters.UserName, GlobalParameters.appId, GlobalParameters.appSecret, 2052);

            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            if (resultType == 1)
            {
                return client;
            }
            else { return null; }

        }

        /// <summary>
        /// 返回json
        /// </summary>
        /// <param name="FID">内码ID</param>
        /// <param name="Number">编码</param>
        /// <param name="MsgError">错误描述及字段</param>
        /// <param name="MsgIsSuccess">是否成功</param>
        /// <param name="Code">错误代码0：默认1：上下文丢失2：没有权限3：操作标识为空4：异常5：单据标识为空 6：数据库操作失败7：许可错误8：参数错误9：指定字段/值不存在10：未找到对应数据11：验证失败12：不可操作13：网控冲突</param>
        /// <returns></returns>
        private static ReturnJson JsonResult(string FID1, string Number, List<Errors> MsgError, bool MsgIsSuccess, int Code, string[] Fentryid)
        {
            var successEntitys = new List<SuccessEntitys>
            {

            };
            var successMessages = new List<SuccessMessages> { };

            var responseStatus = new ResponseStatus()
            {
                ErrorCode = 500,
                IsSuccess = MsgIsSuccess,
                Errors = MsgError,
                MsgCode = Code,
                SuccessEntitys = successEntitys,
                SuccessMessages = successMessages
            };
            var fEntityDetail_Add = new List<FEntityDetail>();
            if (Fentryid.Length > 0)
            {

                for (int i = 0; i < Fentryid.Length; i++)
                {
                    var fEntityDetail = new FEntityDetail()
                    {
                        FentryID = Fentryid[i].ToString()
                    };
                    fEntityDetail_Add.Add(fEntityDetail);
                }
            }
            var needReturnData_List = new List<NeedReturnData>();
            var needReturnData = new NeedReturnData()
            {
                FID = FID1,
                FEntityDetail = fEntityDetail_Add

            };
            needReturnData_List.Add(needReturnData);
            var result = new Result()
            {
                ResponseStatus = responseStatus,
                Id = FID1,
                Number = Number,
                NeedReturnData = needReturnData_List
            };

            var returnJson = new ReturnJson()
            {
                Result = result
            };

            return returnJson;
        }
        /// <summary>
        /// 错误描述
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        private static List<Errors> MsgError(Dictionary<string, string> Msg)
        {
            var errList = new List<Errors>();
            foreach (string item in Msg.Keys)
            {
                var errors = new Errors()
                {
                    FieldName = item,
                    Message = Msg[item],
                    DIndex = 0,
                };
                errList.Add(errors);

            }
            return errList;
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="Desc">错误描述</param>
        /// <param name="DName">操作名称</param>
        /// <param name="BillName">单据名称</param>
        /// <param name="subID">领域编号</param> 应付单=50
        /// <returns></returns>
        public bool GetLog(string Desc, string DName, string BillName, string subID)
        {
            bool Judge = false;
            try
            {
                //保存上机日志
                var logs = new List<LogObject>();
                var log = new LogObject();
                log.pkValue = BillName;
                log.Description = Desc;
                log.OperateName = DName;
                log.ObjectTypeId = "";
                log.SubSystemId = subID;
                log.Environment = OperatingEnvironment.BizOperate;
                logs.Add(log);
                LogServiceHelper.BatchWriteLog(this.KDContext.Session.AppContext, logs);
                //保存文档日志
                Logger.Info(BillName + "-" + DName, Desc);
                Logger.Error(BillName + "-" + DName, Desc, new KDException("?", "金蝶异常......"));
                var logFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\Cloud.log";
                Judge = true;
            }
            catch (Exception)
            {
            }
            return Judge;
        }
    }
}
